package com.sh.test_one.dialog;

import android.app.AlertDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.fragment.app.DialogFragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.sh.test_one.R;
import com.sh.test_one.adapater.SubscriptionAdapter;
import com.sh.test_one.bean.SubscriptionOption;
import com.sh.test_one.listener.OnDialogResultListener;

import java.util.ArrayList;
import java.util.List;

public class CustomDialogFragment extends DialogFragment {

    private RecyclerView recyclerView;
    private SubscriptionAdapter adapter;
    private List<SubscriptionOption> subscriptionOptions;

    private TextView tvCountdown;
    private CountDownTimer countDownTimer;
    private ImageView imageViewVipTitle;

    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // 使用自定义布局
        View view = LayoutInflater.from(getContext()).inflate(R.layout.custom_pay, null);
        view.setBackgroundResource(R.drawable.gradient_background);
        // 初始化组件
        initRecyclerView(view);
        initCountdown(view);
        initVipTitleClick(view);
        // 创建 Dialog
        Dialog dialog = new Dialog(getContext());
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); // 去掉标题栏
        dialog.setContentView(view);
        // 初始化选择值
        if (subscriptionOptions.size() > 1) {
            // post会等布局完成再执行
            recyclerView.post(() -> {
                View secondItemView = recyclerView.findViewHolderForAdapterPosition(1).itemView;
                if (secondItemView != null) {
                    handleItemClick(secondItemView, 1, subscriptionOptions.get(1));
                }
            });
        }
        return dialog;
    }

    private void initVipTitleClick(View view) {
        imageViewVipTitle = view.findViewById(R.id.image_view_vip_title);
        imageViewVipTitle.setOnClickListener(v -> showVipInfoDialog());
    }

    private void showVipInfoDialog() {
        new AlertDialog.Builder(getContext())
                .setTitle("VIP提示")
                .setMessage("买了就不能反悔了噶！！！！！")
                .setPositiveButton("确定", null)
                .setNegativeButton("取消", null)
                .show();
    }

    private void initCountdown(View view) {
        tvCountdown = view.findViewById(R.id.tv_countdown);
        startCountdown(30 * 60 * 1000, 1000); // 30分钟倒计时，每秒更新一次
    }

    private void startCountdown(long totalTime, long interval) {
        if (countDownTimer != null) {
                countDownTimer.cancel();
        }
        countDownTimer = new CountDownTimer(totalTime, interval) {
            @Override
            public void onTick(long millisUntilFinished) {
                updateCountdownText(millisUntilFinished);
            }

            @Override
            public void onFinish() {
                tvCountdown.setText("倒计时结束");
            }
        }.start();
    }

    private void updateCountdownText(long millisUntilFinished) {
        long seconds = millisUntilFinished / 1000;
        long minutes = seconds / 60;
        seconds = seconds % 60;
        tvCountdown.setText(String.format("等待付款：%02d分%02d秒", minutes, seconds));
    }

    private void initRecyclerView(View view) {
        recyclerView = view.findViewById(R.id.recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));

        subscriptionOptions = new ArrayList<>();
        subscriptionOptions.add(new SubscriptionOption("1个月", 22, 2));
        subscriptionOptions.add(new SubscriptionOption("3个月", 6, 3));
        subscriptionOptions.add(new SubscriptionOption("12个月", 23, 268));
        subscriptionOptions.add(new SubscriptionOption("12个月", 23, 268));
        subscriptionOptions.add(new SubscriptionOption("12个月", 23, 268));

        adapter = new SubscriptionAdapter(getContext(), subscriptionOptions);
        recyclerView.setAdapter(adapter);

        adapter.setOnItemClickListener(this::handleItemClick);



    }

    private void handleItemClick(View view, int position, SubscriptionOption option) {
        clearAndSetBackgroundColors(view);
        startCountdown(30 * 60 * 1000, 1000); // 重新开始倒计时
        // getActivity()返回依赖的 activity
        if (getActivity() instanceof OnDialogResultListener) {
            ((OnDialogResultListener) getActivity()).onDialogResult("您支付了：", (int)subscriptionOptions.get(position).getDailyPrice());
        }
    }

    private void clearAndSetBackgroundColors(View clickedView) {
        for (int i = 0; i < recyclerView.getChildCount(); i++) {
            View child = recyclerView.getChildAt(i);
            if (child != null) {
                child.setBackgroundResource(R.drawable.pay_item_old);
            }
        }
        clickedView.setBackgroundResource(R.drawable.pay_item_new);
    }




    @Override
    public void onStart() {
        super.onStart();
        Dialog dialog = getDialog();
        if (dialog != null) {
            Window window = dialog.getWindow();
            if (window != null) {
                WindowManager.LayoutParams lp = window.getAttributes();
                lp.width = (int) (getResources().getDisplayMetrics().widthPixels * 0.9); // 设置宽度为屏幕宽度的 90%
                lp.height = (int) (getResources().getDisplayMetrics().heightPixels * 0.7); // 设置高度为屏幕高度的 70%
                window.setAttributes(lp);
                // 确保透明背景没有影响到圆角显示
                window.setBackgroundDrawableResource(android.R.color.transparent);
            }
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
    }
}